#ifndef _SQLCONNPOOL_H
#define _SQLCONNPOOL_H

#include <string>
#include <queue>
#include <mutex>
#include <semaphore.h>
#include <thread>
#include <mysql/mysql.h>
#include <atomic>
#include <assert.h>

class SqlConnPool
{
public:
    static SqlConnPool* getInstance();

    MYSQL* GetConn();
    void FreeConn(MYSQL* conn);
    int GetFreeConnCount();

    void Init(const char* host, int port, const char* user, const char* pwd, const char* dbName, int connSize);

    void ClosePool();

private:
    SqlConnPool();
    ~SqlConnPool();

    SqlConnPool(const SqlConnPool& obj) = delete;
    SqlConnPool& operator=(const SqlConnPool& obj) = delete;
    SqlConnPool(SqlConnPool&& obj) = delete;
    SqlConnPool& operator=(SqlConnPool&& obj) = delete;

    int MAX_CONN_;
    int userCount_;
    int freeCount_;

    std::queue<MYSQL*> connQue_;
    std::mutex mtx_;
    sem_t semId_;

    static std::atomic<SqlConnPool*> connPool;
    static std::mutex m_mutex;
};

#endif